// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
}) // 使用当前云环境

const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const openid = wxContext.OPENID
  let result = {}
  if (event.returnCode == 'SUCCESS' && event.resultCode == 'SUCCESS') {
    const {
      subOpenid, // 小程序用户的openid
      outTradeNo, // 商户号的订单号
      attach,
      totalFee, // fen
      transactionId,
      timeEnd,
    } = event

    const param = JSON.parse(attach)
    const _ = db.command

    if (param.title == '步梯费') {
      db.collection('orders')
        .where({
          outTradeNo
        })
        .update({
          data: {
            stepFee: _.inc(totalFee * 0.01),
            transactionId,
            timeEnd,
            updateTime: new Date().getTime()
          }
        })
    } else if (param.title == '空桶押金') {
      const res = await db.collection('users')
        .where({
          _id: _.eq(param.userId)
        }).get()
      const user = res.data[0]
      const payList = user.barrelPay.list
      for (const pay of payList) {
        if (pay.outTradeNo == outTradeNo && pay.payStatus == 'wait') {
          pay.payStatus = 'success'
          pay.transactionId = transactionId
          pay.timeEnd = timeEnd
          pay.updateTime = new Date().getTime()
          break;
        }
      }

      result = await db.collection('users')
        .where({
          _id: _.eq(param.userId),
          barrelPay: {
            list: _.elemMatch({
              payStatus: _.eq('wait'),
              outTradeNo: _.eq(outTradeNo)
            })
          }
        })
        .update({
          data: {
            barrelPay: {
              list: payList
            }
          }
        })
    }
  }

  return result
}